package testJDBC;

import com.google.protobuf.Message;

import java.sql.*;
import java.text.MessageFormat;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 刘远望
 * Date: 2025-05-14
 * Time: 21:37
 */
public class Demo01_DriverManager {
    public static void main(String[] args) {
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            //1.加载数据厂商提供的驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获取数据库连接
            connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/java113?characterEncodng=utf8&alLowPublicKeyRetrieval=true&useSSL=false"
            , "root", "liuyvanwang");
            //3.创建statement对象
            statement = connection.createStatement();
            //4.定义sql并执行sql语句
            System.out.println("请输入学生姓名:");
            Scanner scanner = new Scanner(System.in);
            //接受输入
            String name = scanner.next();

            String sql = "select student_id, sn, name, mail, class_id from student where name = '"+ name +"'";
            //5.执行sql，获得查询结果
            resultSet = statement.executeQuery(sql);
            //6.对数据结果集进行遍历
            while (resultSet.next()) {
                //获取学生的各个字段
                long Id = resultSet.getLong(1);
                String Sn = resultSet.getString(2);
                String Name = resultSet.getString(3);
                String Mail = resultSet.getString(4);
                long ClassId = resultSet.getLong(5);
                System.out.println(MessageFormat.format("学生编号 = {0}, 学号 = {1}, 姓名 = {2}, 邮箱 = {3}, 班级 = {4}"
                                                        , Id, Sn, Name, Mail, ClassId));
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //从后往前依次释放资源
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (statement != null) {
                try {
                    statement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
